package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * @Description 线程池配置类
 **/
@Configuration
public class ThreadPoolConfig {
    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = 5;

    /**
     * 最大线程数
     */
    private static final int MAXIMUM_POOL_SIZE = 10;

    /**
     * 空闲线程存活时间
     */
    private static final int KEEP_ALIVE_TIME = 30;

    /**
     * 线程池阻塞等待队列
     */
    private BlockingQueue<Runnable> blockingQueue;

    /**
     * 线程池拒绝策略
     */
    private RejectedExecutionHandler rejectedExecutionHandler;

    @Bean
    public Executor serviceExecutor() {

        /** 指定线程池等待队列为有界先进先出队列 **/
        blockingQueue = new ArrayBlockingQueue<>(5);

        /** 指定线程池的拒绝策略为由调用线程自己执行 **/
        rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();

        return new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                blockingQueue,
                new MyThreadFactory(),
                rejectedExecutionHandler
        );
    }
}
